package socket;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * 聊天室客户端—
 */
public class Client {

    private Socket socket;

    public Client() {

        /*
        实例化Socket就是与远端计算机建立2连接的过程
        这里的参数1：服务器计算机的ip地址参数2：服务器
         */
        try {
            System.out.println("正在连接服务端...");
            socket = new Socket("localhost", 8088);
            System.out.println("与服务端建立连接");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        try {
            ServerHandler handler =new ServerHandler();
            Thread t =new Thread(handler);
            t.start();
            t.setDaemon(true);//守护线程，我们不给服务器发消息了，该线程也结束了
            Scanner sc = new Scanner(System.in);
            //创建一个低级流 来向服务端输出内容
            OutputStream out = socket.getOutputStream();
            //转换输出流 将写出的字符转换为字节
            OutputStreamWriter osw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
            BufferedWriter bw = new BufferedWriter(osw);
            //使用缓冲字符输出流 输出字符 添加行刷新
            PrintWriter pw = new PrintWriter(bw, true);

            while (true) {
                System.out.println("输入要说的话");
                String next = sc.next();
                if ("exit".equalsIgnoreCase(next)) {
                    break;
                }
                pw.println(next);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                //关闭与服务器的连接进行挥手操作
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Client client = new Client();
        client.start();

    }
    private class ServerHandler implements Runnable{
        @Override
        public void run() {
            try {
                //通过socket获得输入流
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);
                String line = br.readLine();
                System.out.println(line);
                //读取服务端返回的话
                String message;
                while ((message=br.readLine())!=null){
                    System.out.println(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
